<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="showAdd = true"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="35%"
    >
        <el-form :model="createForm" ref="createForm" :rules="addRules" label-width="150px">
            <el-form-item label="电批条码" prop="facilityBarcode" >
                <el-input v-model="createForm.facilityBarcode" class="ul-item" type="textarea" @change="getstandardValueOfTorque" autosize/>
            </el-form-item>
            <el-form-item label="外观点检部分" prop="spotAudit">
                <el-select
                    v-model="createForm.spotAudit"
                    class="ul-item"
                    @change="changeSpotAudit"
                    >
                    <el-option
                        v-for="(item,index) in spotAuditList"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="力矩标准值" prop="standardValueOfTorque" required>
                <el-input v-model="createForm.standardValueOfTorque" class="ul-item"/>
            </el-form-item>
            <el-form-item label="力矩范围" prop="standardScope" required>
                <el-input v-model="createForm.standardScope" class="ul-item"/>
            </el-form-item>
            <!-- <el-form-item label="力矩测试值1" prop="momentTestValue1" required>
                <el-input v-model="createForm.momentTestValue1" class="ul-item"/>
            </el-form-item>
            <el-form-item label="力矩测试值2" prop="momentTestValue2" required>
                <el-input v-model="createForm.momentTestValue2" class="ul-item"/>
            </el-form-item>
            <el-form-item label="力矩测试值3" prop="momentTestValue3" required>
                <el-input v-model="createForm.momentTestValue3" class="ul-item"/>
            </el-form-item> -->
            <el-form-item label="点检人工号" prop="testJobNumber" required>
                <el-input v-model="createForm.testJobNumber" class="ul-item"/>
            </el-form-item>
            <el-form-item label="表面清洁无破损螺钉松动" prop="testItem1">
                <el-select
                    v-model="createForm.testItem1"
                     class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="力矩标识是否清楚" prop="testItem2">
                <el-select
                    v-model="createForm.testItem2"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="通风孔正常无堵塞" prop="testItem3">
                <el-select
                    v-model="createForm.testItem3"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电源线正常无破损" prop="testItem4">
                <el-select
                    v-model="createForm.testItem4"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="是否定低速挡" prop="testItem5">
                <el-select
                    v-model="createForm.testItem5"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电批正反是否转正常" prop="testItem6">
                <el-select
                    v-model="createForm.testItem6"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电批使用噪音否正常" prop="testItem7">
                <el-select
                    v-model="createForm.testItem7"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="刹车装置是否正常" prop="testItem8">
                <el-select
                    v-model="createForm.testItem8"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="接触是否正常" prop="testItem9">
                <el-select
                    v-model="createForm.testItem9"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="外壳金属装置对地电阻值" prop="testItem10">
                <el-select
                    v-model="createForm.testItem10"
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in optionsYn"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input  class="ul-item" clearable type="textarea" :autosize="{ minRows: 1, maxRows: 3}" v-model="createForm.remark" auto-complete="off"></el-input>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >新增</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.facilityBarcode) }"
            v-model="param.facilityBarcode"
            placeholder="工装条码"
        ></el-input>
        <el-select
            clearable
            @keyup.enter.native="getData"
            v-model="param.type"
            style="margin-right: 15px"
            :style="{ width: inputWid(param.type) }"
            >
            <el-option
                v-for="(item,index) in typeList"
                :key="index"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工装条码"  prop="facilityBarcode" align="center"/>
      <el-table-column label="工装名称"  prop="facilityName" align="center"/>
      <el-table-column label="外观点检部分"  prop="spotAudit" align="center"/>
      <el-table-column label="力矩标准值"  prop="standardValueOfTorque" align="center"/>
      <el-table-column label="力矩范围"  prop="standardScope" align="center"/>
      <el-table-column label="力矩测试值1"  prop="momentTestValue1" align="center"/>
      <el-table-column label="力矩测试值2"  prop="momentTestValue2" align="center"/>
      <el-table-column label="力矩测试值3"  prop="momentTestValue3" align="center"/>
      <el-table-column label="力矩平均值"  prop="momentTestValue4" align="center"/>
      <el-table-column label="点检人工号"  prop="testJobNumber" align="center"/>
      <el-table-column label="清洁有无破损"  prop="testItem1" align="center"/>
      <el-table-column label="力矩标识是否清楚"  prop="testItem2" align="center"/>
      <el-table-column label="通风孔是否堵塞"  prop="testItem3" align="center"/>
      <el-table-column label="电源线是否有破损"  prop="testItem4" align="center"/>
      <el-table-column label="是否定低速挡"  prop="testItem5" align="center"/>
      <el-table-column label="批头转动是否正常"  prop="testItem6" align="center"/>
      <el-table-column label="噪音是否过大"  prop="testItem7" align="center"/>
      <el-table-column label="刹车装置是否正常"  prop="testItem8" align="center"/>
      <el-table-column label="接触是否正常"  prop="testItem9" align="center"/>  
      <el-table-column label="外壳金属装置对地电阻值"  prop="testItem10" align="center"/>
      <el-table-column label="备注"  prop="remark" align="center"/>
      <el-table-column label="点检时间"  prop="createTime" align="center"/>
      <el-table-column label="状态"  prop="type" align="center">
        <template slot-scope="scope" >
                {{ scope.row.type == 1 ? '成功'
                :scope.row.type == 2 ? '失败' : '点检中' }}
            </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="100">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { selmomentTest,addmomentTest,delmomentTest,updfacility } from "@/api/processRoute"
export default {
    name: 'frockFixture',
    data () {
        var validateStandardValueOfTorque = (rule, value, callback) => {
            if (!value) {
                callback(new Error('力矩标准值不能为空'));
            } else {
                let numRe = new RegExp('^[-\\+]?([0-9]+\\.?)?[0-9]+$')
                if(!numRe.test(value)) {
                    callback(new Error('力矩标准值必须为数字'))
                }
                callback();
            }
        };
        var validateStandardScope = (rule, value, callback) => {
            if (!value) {
                callback(new Error('范围不能为空'));
            } else {
                let numRe = new RegExp('^[-\\+]?([0-9]+\\.?)?[0-9]+$')
                if(!numRe.test(value)) {
                    callback(new Error('范围必须为数字'))
                }
                callback();
            }
        };
        var validateMomentTestValue1 = (rule, value, callback) => {
            if (!value) {
                callback(new Error('力矩测试值1不能为空'));
            } else {
                let numRe = new RegExp('^[-\\+]?([0-9]+\\.?)?[0-9]+$')
                if(!numRe.test(value)) {
                    callback(new Error('力矩测试值1必须为数字'))
                }
                callback();
            }
        };
        var validateMomentTestValue2 = (rule, value, callback) => {
            if (!value) {
                callback(new Error('力矩测试值2不能为空'));
            } else {
                let numRe = new RegExp('^[-\\+]?([0-9]+\\.?)?[0-9]+$')
                if(!numRe.test(value)) {
                    callback(new Error('力矩测试值2必须为数字'))
                }
                callback();
            }
        };
        var validateMomentTestValue3 = (rule, value, callback) => {
            if (!value) {
                callback(new Error('力矩测试值3不能为空'));
            } else {
                let numRe = new RegExp('^[-\\+]?([0-9]+\\.?)?[0-9]+$')
                if(!numRe.test(value)) {
                    callback(new Error('力矩测试值3必须为数字'))
                }
                callback();
            }
        };
        return {
            typeList:[{name:'成功',id:1},{name:'失败',id:2},{name:'点检中',id:3}],
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                facilityBarcode: '',                      //产品编码
                type: 3,
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            createForm: {},
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                facilityBarcode: [
                    { required: true, message: "工装条码不能为空!", trigger: "change" },
                ],
                spotAudit: [
                    { required: true, message: "外观点检部分不能为空!", trigger: "change" },
                ],
                standardValueOfTorque: [
                    { validator: validateStandardValueOfTorque, trigger: 'blur' }
                    // { required: true, message: "力矩标准值不能为空!", trigger: "change" },
                ],
                standardScope: [
                    { validator: validateStandardScope, trigger: 'blur' }
                    // { required: true, message: "范围不能为空!", trigger: "change" },
                ],
                momentTestValue1: [
                    { validator: validateMomentTestValue1, trigger: 'blur' }
                    // { required: true, message: "力矩测试值1不能为空!", trigger: "change" },
                ],
                momentTestValue2: [
                    { validator: validateMomentTestValue2, trigger: 'blur' }
                    // { required: true, message: "力矩测试值2不能为空!", trigger: "change" },
                ],
                momentTestValue3: [
                    { validator: validateMomentTestValue3, trigger: 'blur' }
                    // { required: true, message: "力矩测试值3不能为空!", trigger: "change" },
                ],
                testJobNumber: [
                    { required: true, message: "点检人工号不能为空!", trigger: "change" },
                ],
                testItem1: [
                    { required: true, message: "清洁有无破损不能为空!", trigger: "change" },
                ],
                testItem2: [
                    { required: true, message: "力矩标识是否清楚不能为空!", trigger: "change" },
                ],
                testItem3: [
                    { required: true, message: "通风孔是否堵塞不能为空!", trigger: "change" },
                ],
                testItem4: [
                    { required: true, message: "电源线是否有破损不能为空!", trigger: "change" },
                ],
                testItem5: [
                    { required: true, message: "是否定低速挡不能为空!", trigger: "change" },
                ],
                testItem6: [
                    { required: true, message: "批头转动是否正常不能为空!", trigger: "change" },
                ],
                testItem7: [
                    { required: true, message: "噪音是否过大不能为空!", trigger: "change" },
                ],
                testItem8: [
                    { required: true, message: "刹车装置是否正常不能为空!", trigger: "change" },
                ],
                testItem9: [
                    { required: true, message: "接触是否正常不能为空!", trigger: "change" },
                ],
                testItem10: [
                    { required: true, message: "外壳金属装置对地电阻值不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            userInfo: this.$store.state.user.userInfo,
            spotAuditList: ['OK','NG'],
            optionsYn: ['是','否'],      //是否类型
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.facilityBarcode){ query.facilityBarcode = this.param.facilityBarcode}
            if(this.param.type){ query.type = this.param.type}
            let data = await selmomentTest(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.total
            this.tableInfo = data.data.records
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
            this.listQuery.page = 1
            this.listQuery.limit = val
            this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
            this.listQuery.page = val
            this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            facilityBarcode: '工装条码',
            facilityName: '工装名称',
            spotAudit: '外观点检部分',
            standardValueOfTorque: '力矩标准值',
            standardScope: '范围',
            momentTestTalue1: '力矩测试值1',
            momentTestValue2: '力矩测试值2',
            momentTestValue3: '力矩测试值3',
            momentTestValue4: '力矩平均值',
            testJobNumber: '点检人工号',
            testItem1: '清洁有无破损',
            testItem2: '力矩标识是否清楚',
            testItem3: '通风孔是否堵塞',
            testItem4: '电源线是否有破损',
            testItem5: '是否定低速挡',
            testItem6: '批头转动是否正常',
            testItem7: '噪音是否过大',
            testItem8: '刹车装置是否正常',
            testItem9: '接触是否正常',
            testItem10: '外壳金属装置对地电阻值',
            remark: '备注',
            createTime: '点检时间'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.facilityBarcode){ query.facilityBarcode = this.param.facilityBarcode}
          let arr = await selmomentTest(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.records.length) return this.$message.error('暂无数据')
          const { header, data } = this.transformDat(this.setSort(arr.data.records))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '工装点检维修保养excel', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              facilityBarcode: item.facilityBarcode,
              facilityName: item.facilityName,
              spotAudit: item.spotAudit,
              standardValueOfTorque: item.standardValueOfTorque,
              standardScope: item.standardScope,
              momentTestTalue1: item.momentTestTalue1,
              momentTestValue2: item.momentTestValue2,
              momentTestValue3: item.momentTestValue3,
              momentTestValue4: item.momentTestValue4,
              testJobNumber: item.testJobNumber,
              testItem1: item.testItem1,
              testItem2: item.testItem2,
              testItem3: item.testItem3,
              testItem4: item.testItem4,
              testItem5: item.testItem5,
              testItem6: item.testItem6,
              testItem7: item.testItem7,
              testItem8: item.testItem8,
              testItem9: item.testItem9,
              testItem10: item.testItem10,
              remark: item.remark,
              createTime: item.createTime
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                facilityBarcode: '',                      //产品编码
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // let avr = (parseFloat(this.createForm.momentTestValue1)+parseFloat(this.createForm.momentTestValue2)+parseFloat(this.createForm.momentTestValue3))/3
                    // if((avr>=parseFloat(this.createForm.standardValueOfTorque)-parseFloat(this.createForm.standardScope)) && avr<=(parseFloat(this.createForm.standardValueOfTorque)+parseFloat(this.createForm.standardScope))){
                        this.submitprocess()
                    // } else {
                    //     this.$confirm('根据显示的数据，力矩测试结果不正常，是否更改资源状态为待维修?', '警告', {
                    //         confirmButtonText: '确定',
                    //         cancelButtonText: '取消',
                    //         type: 'warning'
                    //     }).then(() => {
                    //         this.unqualified()
                    //     }).catch(() => {
                    //         this.$message({
                    //         type: 'info',
                    //         message: '已取消'
                    //         })
                    //     })
                    // }
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            const data = await addmomentTest(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await delmomentTest({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        async unqualified(){
            let data = await updfacility({facilityBarcode: this.createForm.facilityBarcode,type: '待维修'})
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(res.msg)
            this.submitprocess()
        },
        changeSpotAudit(val){
            console.log(val)
            if(val == 'OK'){
                this.$set(this.createForm, 'testItem1','是')
                this.$set(this.createForm, 'testItem2','是')
                this.$set(this.createForm, 'testItem3','是')
                this.$set(this.createForm, 'testItem4','是')
                this.$set(this.createForm, 'testItem5','是')
                this.$set(this.createForm, 'testItem6','是')
                this.$set(this.createForm, 'testItem7','是')
                this.$set(this.createForm, 'testItem8','是')
                this.$set(this.createForm, 'testItem9','是')
                this.$set(this.createForm, 'testItem10','是')
            } else {
                this.$set(this.createForm, 'testItem1','否')
                this.$set(this.createForm, 'testItem2','否')
                this.$set(this.createForm, 'testItem3','否')
                this.$set(this.createForm, 'testItem4','否')
                this.$set(this.createForm, 'testItem5','否')
                this.$set(this.createForm, 'testItem6','否')
                this.$set(this.createForm, 'testItem7','否')
                this.$set(this.createForm, 'testItem8','否')
                this.$set(this.createForm, 'testItem9','否')
                this.$set(this.createForm, 'testItem10','否')
            }
        },
        getstandardValueOfTorque(){
            if(!this.createForm.facilityBarcode) return console.log('电批条码为空')
            console.log(this.createForm.facilityBarcode,parseFloat(this.createForm.facilityBarcode.split('-')[2]))
            this.$set(this.createForm, 'standardValueOfTorque',parseFloat(this.createForm.facilityBarcode.split('-')[2]))
            this.$set(this.createForm, 'standardScope',(parseFloat(this.createForm.facilityBarcode.split('-')[2])*0.1).toFixed(1))
        }
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
